from rest_framework.views import exception_handler as drf_exception_handler
import logging
from django.db import DatabaseError
from redis.exceptions import RedisError
from rest_framework.response import Response
from rest_framework import status

# 获取配置中的自定义logger，用于记录日志
logger = logging.getLogger('django')

# 修改默认使用的异常处理函数捕捉异常进行处理
def exception_handler(exc, context):
    # 先交给默认的处理器处理
    response = drf_exception_handler(exc, context)
    # 若返回值为None代表不是序列化器的异常
    if response is None:
        view = context['view']
        if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
            # 数据库异常
            logger.error('[{}] {}'.format(view, exc))
            response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
    return response
